package com.gx.smart.construction.ui.common.util;

import android.content.Context;
import android.util.Log;

import androidx.datastore.preferences.core.MutablePreferences;
import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.core.PreferencesKeys;
import androidx.datastore.preferences.rxjava3.RxPreferenceDataStoreBuilder;
import androidx.datastore.rxjava3.RxDataStore;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.Utils;
import com.gx.smart.common.util.AppConfig;

import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.functions.Consumer;

/**
 * @author: xiaosy
 * 时间: 2021/11/24
 * @Description: 数据存储
 * @Version: 1.0
 **/
public class DataStoreHelper {
    private RxDataStore<Preferences> dataStore;
    private Context context;
    public Preferences.Key<String> AREA_NAME_KEY = PreferencesKeys.stringKey(AppConfig.AREA_NAME);
    public Preferences.Key<String> SYS_TENANT_NO_KEY = PreferencesKeys.stringKey(AppConfig.SYS_TENANT_NO);

    private static class SingleTonHolder {
        private static final DataStoreHelper INSTANCE = new DataStoreHelper();
    }

    public static DataStoreHelper getInstance() {
        return SingleTonHolder.INSTANCE;
    }

    private DataStoreHelper() {
        this.dataStore =
                new RxPreferenceDataStoreBuilder(Utils.getApp(), "pref_settings").build();
    }
//    public DataStoreHelper(Context context) {
//
//    }


    /**
     * 将值写入Preference
     */
    public void writeValue(Preferences.Key<String> KEY,String value) {
        Single<Preferences> updateResult = dataStore.updateDataAsync(prefsInt -> {
            MutablePreferences mutablePreferences = prefsInt.toMutablePreferences();
            String currentInt = prefsInt.get(KEY);
            Log.d("xsy", "writeValue: currentInt " + currentInt);
            mutablePreferences.set(KEY, value);
            return Single.just(mutablePreferences);

        });
        updateResult.subscribe(new Consumer<Preferences>() {
            @Override
            public void accept(Preferences preferences) throws Exception {
                if (preferences != null) {
                    String item = preferences.get(KEY);
                    Log.d("xsy", "accept: " + item);
                }
            }
        });
    }


    public Flowable<String> readValue(Preferences.Key<String> KEY) {
        Flowable<String> flow =
                dataStore.data().map(prefs ->
                        prefs.get(KEY)
                );

        return flow;
    }
}
